package com.ruoyi.partybuilding.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.partybuilding.common.EQueryController;
import com.ruoyi.partybuilding.common.PageSort;
import com.ruoyi.partybuilding.domain.ScoreType;
import lombok.var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.*;
/**
 * 积分类型Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "积分类型-规则")
@RestController
@RequestMapping("/partybuilding/ScoreType")
public class ScoreTypeController extends EQueryController<ScoreType>
{

    /**
     * 查询积分类型列表
     */
    @ApiOperation("列表")
    //@PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScoreType review, PageSort pageRequest) {
        return super.list(review, pageRequest);
    }

    @ApiOperation("树列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:list')")
    @GetMapping("/treeList")
    public R<List<ScoreType>> treeList(ScoreType review) {
//        var list = super.queryPage(review, null);
//        var root = new ArrayList<ScoreType>();
//        list.getData().forEach(p -> {
//            if (p.getParentId() == null)
//                root.add(p);
//            var parent = root.stream().filter(x -> Objects.equals(x.getId(), p.getParentId())).findFirst();
//            parent.ifPresent(scoreType -> scoreType.getChildren().add(p));
//        });
        return R.ok();
    }

    /**
     * 导出积分类型列表
     */
    @ApiOperation("导出")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:export')")
    @Log(title = "积分类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScoreType review, PageDomain pageRequest) {
        super.export(review,pageRequest,null,response);
    }

    /**
     * 获取积分类型详细信息
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:query')")
    @GetMapping(value = "/{id}")
    public R<ScoreType> getInfo(@PathVariable("id") Long id) {

        return super.getInfo(id);
    }


    @ApiOperation(value = "新建积分分类",notes = "只传name和type即可；type:0个人积分，1组织积分")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:add')")
    @Log(title = "积分类型", businessType = BusinessType.INSERT)
    @PostMapping("/addCategory")
    public R<Long> addCategory(@RequestBody ScoreType reviewDto) {

        var name = reviewDto.getName();
        var type = reviewDto.getType();
        name = StringUtils.trim(name);
        var vr = baseVaild(name, type);
        if (!R.isSuccess(vr))
            return vr;
        var review = new ScoreType();
        review.setName(name);
        review.setStatus(1l);
        review.setLevel(0l);
        review.setWayType(0l);
        review.setType(type);

        return super.add(review);
    }
    R baseVaild(String name,Long type){
        if(type!=0&&type!=1)
            return R.fail("类型错误");
        if(StringUtils.isEmpty(name))
            return R.fail("名称错误");
        String finalName = name;
        var isRepeat = queryHelper.queryable(ScoreType.class)
                .where(p -> p.eq(ScoreType::getName, finalName))
                .any();
        if (isRepeat)
            return R.fail("重复的名称");
        return R.ok();
    }
    @ApiOperation("新建积分规则")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:add')")
    @Log(title = "新建积分规则", businessType = BusinessType.INSERT)
    @PostMapping("/addRule")
    public R<Long> addRule(@Validated @RequestBody ScoreType review) {

        review.setName(StringUtils.trim(review.getName()));
        var vr=baseVaild(review.getName(), review.getType());
        if (!R.isSuccess(vr))
            return vr;
        review.setLevel(1l);
        review.setWayType(0l);
        return super.add(review);
    }
    @ApiOperation(value = "启停积分规则",notes = "")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:edit')")
    @Log(title = "积分类型", businessType = BusinessType.UPDATE)
    @PostMapping("/onoffRule")
    public R  onoffRule(Long scoreTypeId,Long onoff) {
       var re= super.getInfo(scoreTypeId);
       var sc=re.getData();
       sc.setStatus(onoff);
       super.edit(sc);
       return R.ok();
    }

    /**
     * 修改积分类型
     */
    @ApiOperation(value = "积分分类规则修改",notes = "只能更新部分内容")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:edit')")
    @Log(title = "积分类型", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public R<Long> edit(@RequestBody ScoreType review) {
        var re = getInfo(review.getId());
        var old = re.getData();
        if (old.getLevel() == 0) {
            old.setName(review.getName());
        } else if (old.getLevel() == 1) {
            old.setBasisScore(review.getBasisScore());
            old.setHighScore(review.getHighScore());
            old.setScoreDayUp(review.getScoreDayUp());
            old.setStatus(review.getStatus());
        }
        return super.edit(old);
    }


    /**
     * 删除积分类型
     */
    @ApiOperation(value = "删除",notes = "分类下有子项，不允许删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:ScoreType:remove')")
    @Log(title = "积分类型", businessType = BusinessType.DELETE)
    @PostMapping("remove/{id}")
    public R<Long> remove(@PathVariable("id") Long id) {

        var re = super.getInfo(id);
        if (re.getData() == null)
            return R.fail("找不到id对应项");
        if (re.getData().getLevel() == 0) {
            var existChild = queryHelper.queryable(ScoreType.class)
                    .where(p -> p.eq(ScoreType::getLevel, 1).eq(ScoreType::getParentId, id))
                    .any();
            if (existChild)
                return R.fail("分类有规则不允许删除分类");
        }
        return super.remove(re.getData());
    }

}

